import { app, BrowserWindow, ipcMain, session } from "electron";
import { join } from "path";

let giteeWindow: BrowserWindow | null = null;
let mainWindow: BrowserWindow | null = null;

function createWindow(): void {
  // Create the browser window.
  mainWindow = new BrowserWindow({
    width: 900,
    height: 670,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === "linux"
      ? {
          icon: join(__dirname, "../../build/icon.png"),
        }
      : {}),
    webPreferences: {
      preload: join(__dirname, "../preload/index.js"),
      contextIsolation: true,
      nodeIntegration: false,
      sandbox: false,
    },
  });

  mainWindow.on("ready-to-show", () => {
    mainWindow?.show();
    // 开发环境下自动打开开发者工具
    if (process.env.NODE_ENV === "development") {
      mainWindow?.webContents.openDevTools();
    }
  });

  // Load the remote URL for development or the local html file for production.
  if (process.env.NODE_ENV === "development") {
    mainWindow.loadURL(
      process.env["ELECTRON_RENDERER_URL"] || "http://localhost:5173"
    );
  } else {
    mainWindow.loadFile(join(__dirname, "../renderer/index.html"));
  }
}

// 创建 Gitee 窗口并获取 Cookie
async function createGiteeWindow(): Promise<void> {
  if (giteeWindow) {
    giteeWindow.close();
  }

  giteeWindow = new BrowserWindow({
    width: 1024,
    height: 768,
    show: true,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
    },
  });

  await giteeWindow.loadURL("https://gitee.com");

  // 等待页面加载完成
  return new Promise((resolve) => {
    giteeWindow?.webContents.on("did-finish-load", () => {
      setTimeout(resolve, 2000); // 额外等待2秒确保页面完全加载
    });
  });
}

app.whenReady().then(() => {
  // 注册 get-cookie 事件处理器
  ipcMain.handle("get-cookie", async (event, params) => {
    try {
      console.log("Received get-cookie request with params:", params);

      // 先打开 Gitee
      await createGiteeWindow();

      // 获取 Cookie
      const cookies = await session.defaultSession.cookies.get({
        url: params.url,
        name: params.name,
      });

      console.log("Found cookies:", cookies);

      // 关闭 Gitee 窗口
      if (giteeWindow) {
        giteeWindow.close();
        giteeWindow = null;
      }

      return cookies.length > 0 ? cookies[0].value : null;
    } catch (error) {
      console.error("Error getting cookie:", error);
      if (giteeWindow) {
        giteeWindow.close();
        giteeWindow = null;
      }
      throw error;
    }
  });

  createWindow();

  app.on("activate", function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

// In this file you can include the rest of your app's specific main process code.
// You can also put them in separate files and require them here.
